<?php

namespace Summer\Box\Http\Controllers;

use Illuminate\Routing\Controller;
use RainLab\User\Models\User as UserModel;
use RLuders\JWTAuth\Classes\JWTAuth;
use Summer\Box\Models\BoxItemModel;
use Summer\Box\Models\BoxOrderModel;
use Summer\Box\Models\Settings as BoxSettings;
use Summer\Hjd\Classes\BonusApi;
use Summer\Hjd\Classes\CommonApi;
use Summer\Hjd\Models\BonusRuleModel;
use Summer\Hjd\Models\WalletModel;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Input;
use Config;
use Db;
use Cache;
use Exception;
use Carbon\Carbon;
use Summer\Location\Models\UserAddressModel;
use System\Models\File as FileModel;

class OrderController extends Controller
{
    use ApiReturn;

    /**
     * 创建订单
     */
    public function create(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $item_id=Input::get('item_id');
        if(empty($item_id)){
            return $this->apiError('缺少参数');
        }
        //先上锁
        $item_cache_key='box_item_'.$item_id;
        $item_cache_val=Cache::get($item_cache_key, 'unlock');
        if($item_cache_val=='lock'){
            return $this->apiError('抢购排队中');
        }
        //上锁
        Cache::put($item_cache_key, 'lock');
        //其他判断，失败后要解锁,要不然就等上架通过后解锁
        try {
            $item=BoxItemModel::where('id',$item_id)->first();
            if($item->status!=1){
                throw new Exception('盲盒已失效');
            }
            if($item->is_shangjia!=1){
                throw new Exception('盲盒已下架');
            }
            if($item->user_id==$user->id){
                throw new Exception('不能购买自己的盲盒');
            }

            //需要填写地址和银行信息
            if (empty($user->bank_number)){
                throw new Exception('请完善银行信息');
            }
            $address_count=UserAddressModel::where('user_id',$user->id)->count();
            if(!$address_count){
                throw new Exception('请完善收货地址');
            }

            //每日限购
            $bc_day_can=BonusRuleModel::where('slug','day_can')->first();
            if($bc_day_can->status==1){//开启限制
                //zp修改，按场次类型限制
                if($item->type==1){
                    $day_can=$bc_day_can->rule_value;
                }elseif($item->type==2){
                    $day_can=$bc_day_can->rule_a;
                }
                $day_count=BoxOrderModel::where('buy_uid',$user->id)
                    ->whereHas('item',function ($iq) use($item){
                        $iq->where('type',$item->type);
                    })
                    ->whereDate('created_at',Carbon::today())->count();
                if($day_count>=$day_can){
                    throw new Exception('您今天该类型盲盒抢购数量已达上限');
                }
            }

            //活动时间限制
            $slug=Input::get('slug');
            if(empty($slug)){
                throw new Exception('缺少场次参数');
            }
            if(!in_array($slug,[1,2,3])){
                throw new Exception('场次参数错误');
            }
            if(in_array($slug,[1,2])){
                if ($slug!=$item->type){
                    throw new Exception('该盲盒于该场次不匹配');
                }
            }
            $box_settings= BoxSettings::instance();
            $sessions=$box_settings->sessions;
            $sessions_arr=[];
            foreach ($sessions as $sv){
                $sessions_arr[$sv['slug']]=$sv;
            }
            $begin_time=$sessions_arr[$slug]['begin_time'];
            $end_time=$sessions_arr[$slug]['end_time'];
            $today_date_str=Carbon::today()->toDateString();
            $begin_time_str=$today_date_str." ".$begin_time;
            $end_time_str=$today_date_str." ".$end_time;
            $begin = new Carbon($begin_time_str);
            $end = new Carbon($end_time_str);
            $now=Carbon::now();
            if(!$now->between($begin,$end)){
                throw new Exception('该场次已结束或未开始');
            }
            //判断完成,先修改为下架状态。
            $item->is_shangjia=0;
            $item->save();
            //价格设置
            $bc_pay_ratio=BonusRuleModel::where('slug','pay_ratio')->first();
            $xianjin_ratio=$bc_pay_ratio->rule_value;//现金支付比例
            $jifen_ratio=$bc_pay_ratio->rule_a;//积分支付比例
            $xianjin_pay=$item->price*$xianjin_ratio*0.01;
            $jifen_pay=$item->price*$jifen_ratio*0.01;
            $bc_shangjia_fee=BonusRuleModel::where('slug','shangjia_fee')->first();
            $shangjia_ratio=$bc_shangjia_fee->rule_value;//上架费支付比例
            $shangjia_pay=$item->price*$shangjia_ratio*0.01;
            $bc_yijia=BonusRuleModel::where('slug','yijia')->first();
            $sell_ratio=$bc_yijia->rule_value;//溢价比例
            $sell_money=$item->price*($sell_ratio*0.01+1);
//            $bc_heart=BonusRuleModel::where('slug','heart')->first();
//            $pre_ratio=$sell_ratio-$shangjia_ratio-$bc_heart->rule_value;//预收益比例=溢价-上架费-爱心购
//            $pre_money=$item->price*$pre_ratio*0.01;
            //处理上一周期的订单
            $last_order=BoxOrderModel::where('item_id',$item->id)->orderBy('id','DESC')->first();
            if($last_order){
                //上架中的订单设置成已完成
                if($last_order->status==4&&$last_order->status_slug=='shangjia_ing'){
                    $last_order->status=-1;//完成和拆分也在上架中展示//zp修改 订单完成以后  数据清零
                    $last_order->status_slug='finish';
                    $last_order->save();
                }
                //买入时的积分价格
                $jifen_buy=$last_order->jifen_pay;
                $total_buy=$last_order->total;
            }
            //创建订单
            $order=new BoxOrderModel();
            $order->item_id=$item->id;
            $order->type=$item->type;
            $order->sell_uid=$item->user_id;
            $order->buy_uid=$user->id;
            $order->total=$item->price;
            $order->total_buy=$total_buy??$item->price;
            $order->xianjin_pay=$xianjin_pay;
            $order->xianjin_is_pay=0;
            $order->jifen_pay=$jifen_pay;
            $order->jifen_buy=$jifen_buy??$jifen_pay;
            $order->jifen_is_pay=0;
            $order->shangjia_pay=$shangjia_pay;
            $order->shangjia_is_pay=0;
            $order->sell_money=$sell_money;
//            $order->pre_money=$pre_money;
            $order->status=1;
            $order->status_slug="needpay_jifen";
            $order->is_check=0;

            $order->save();
            return $this->apiSuccess('操作成功');
        }catch (Exception $e) {
            //解锁
            Cache::put($item_cache_key, 'unlock');
            return $this->apiError($e->getMessage());
        }





    }


    /**
     * 推广订单列表
     */
    public function tjindex(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $page_size=Input::get('page_size')??20;
        $page=Input::get('page')??1;

        $tj_type=Input::get('tj_type')??'today';
        //推荐的ids
        $tjdids=[];
        $tjdids=UserModel::where('tuid',$user->id)->pluck('id');
        $query=BoxOrderModel::select();
        $query->with(['item','buyuser']);
        $query->whereIn('buy_uid',$tjdids);
        if($tj_type=='today'){
            $query->whereDate('created_at',Carbon::today());
        }
        $query->where('status','>',2);
        $query->orderBy('id','DESC');
        $records=$query->paginate($page_size,$page);
        $order_status_slug_config=Config::get('summer.box::order_status_slug');
        $records->each(function ($record) use ($order_status_slug_config){
            $record->status_name=$order_status_slug_config[$record->status_slug]['title'];
            $record->item->cover=url('/storage/app/media'.$record->item->cover);
        });
        $rdata['records']=$records;
        return $this->apiSuccess('操作成功',$rdata);

    }
    /**
     * 订单列表
     */
    public function index(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $page_size=Input::get('page_size')??20;
        $page=Input::get('page')??1;
        $status=Input::get('status');
        if(!$status){
            return $this->apiError('参数错误');
        }
        $query=BoxOrderModel::select();
        $query->with(['item','selluser','buyuser']);

        $query->where('buy_uid',$user->id);

//        if(in_array($status,[1,3,4])){
//            $query->where('buy_uid',$user->id);
//        }
//        if(in_array($status,[2])){
//            $query->where('sell_uid',$user->id);
//        }
        $query->where('status',$status);
        $query->orderBy('id','DESC');
        $records=$query->paginate($page_size,$page);
        $order_status_slug_config=Config::get('summer.box::order_status_slug');
        $records->each(function ($record) use ($order_status_slug_config){
            $record->btns=$order_status_slug_config[$record->status_slug]['btns']['buy'];
            $record->status_name=$order_status_slug_config[$record->status_slug]['title'];
            $record->item->cover=url('/storage/app/media'.$record->item->cover);
        });
        $rdata['records']=$records;
        return $this->apiSuccess('操作成功',$rdata);

    }

    /**
     * 订单列表[卖家]
     */
    public function sell_index(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $page_size=Input::get('page_size')??20;
        $page=Input::get('page')??1;

        $query=BoxOrderModel::select();
        $query->with(['item','selluser','buyuser']);

        $query->where('sell_uid',$user->id);
        $query->whereIn('status',[1,2]);
        $query->orderBy('id','DESC');
        $records=$query->paginate($page_size,$page);
        $order_status_slug_config=Config::get('summer.box::order_status_slug');
        $records->each(function ($record) use ($order_status_slug_config){
            $record->btns=$order_status_slug_config[$record->status_slug]['btns']['sell'];
            $record->status_name=$order_status_slug_config[$record->status_slug]['title'];
            $record->item->cover=url('/storage/app/media'.$record->item->cover);
        });
        $rdata['records']=$records;
        return $this->apiSuccess('操作成功',$rdata);

    }


    /**
     * 订单详情
     */
    public function preview(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('order_id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $query=BoxOrderModel::select();
        $query->with(['item','selluser','buyuser','pay_cover']);
        $query->where(function ($q) use($user){
            $q->where('sell_uid',$user->id)->orWhere('buy_uid',$user->id);
        });
        $query->where('id',$order_id);
        $record=$query->first();
        if(!$record){
            return $this->apiError('您没有该订单');
        }
        $order_status_slug_config=Config::get('summer.box::order_status_slug');
        $record->status_name=$order_status_slug_config[$record->status_slug]['title'];
        $record->item->cover=url('/storage/app/media'.$record->item->cover);
        $rdata['record']=$record;
        return $this->apiSuccess('操作成功',$rdata);
    }

    /**
     * 支付积分部分
     * @param JWTAuth $auth
     */
    public function pay_jifen(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('order_id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $order=BoxOrderModel::where('id',$order_id)->where('buy_uid',$user->id)->where('status',1)->where('status_slug','needpay_jifen')->first();
        if(!$order){
            return $this->apiError('订单信息获取失败');
        }
        $item=BoxItemModel::where('id',$order->item_id)->where('user_id',$order->sell_uid)->where('status',1)->first();
        if(!$item){
            return $this->apiError('盲盒信息获取失败');
        }
        $currency_slug='cash';//现金钱包。根据需求修改或配置
        $pay_money=$order->jifen_pay;

        //收款只能收自己支付的积分部分
        $get_money=$order->jifen_buy??$order->jifen_pay;
        //余额判断
        $balance=WalletModel::where('currency_slug',$currency_slug)->where('user_id',$user->id)->value('balance');
        if($pay_money>$balance){
            return $this->apiError('余额不足');
        }
        Db::beginTransaction();
        try {
            //支付积分
            $commonapi=new CommonApi();
            $commonapi->settleDetailed($order->buy_uid,$order->sell_uid,$pay_money,0,$currency_slug,[
                'change_slug'=>'box_pay',
                'table_id'=>$order->id,
                'table_name'=>'summer_box_orders'
            ]);
            //支付收款
            $commonapi=new CommonApi();
            $commonapi->settleDetailed($order->sell_uid,$order->buy_uid,$get_money,1,$currency_slug,[
                'change_slug'=>'box_shou',
                'table_id'=>$order->id,
                'table_name'=>'summer_box_orders'
            ]);
            //改变订单状态
            $order->jifen_is_pay=1;
            $order->jifen_pay_at=Carbon::now();
            $order->status_slug='needpay_xianjin';
            $order->save();
            Db::commit();
            return $this->apiSuccess('操作成功');
        }catch (Exception $e) {
            Db::rollBack();
            return $this->apiError($e->getMessage());
        }
    }
    /**
     * 支付现金部分
     * @param JWTAuth $auth
     */
    public function pay_xianjin(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('order_id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $order=BoxOrderModel::where('id',$order_id)->where('buy_uid',$user->id)->where('status',1)->where('status_slug','needpay_xianjin')->first();
        if(!$order){
            return $this->apiError('订单信息获取失败');
        }
        $item=BoxItemModel::where('id',$order->item_id)->where('user_id',$order->sell_uid)->where('status',1)->first();
        if(!$item){
            return $this->apiError('盲盒信息获取失败');
        }
        $pay_cover_id=Input::get('pay_cover_id',0);
        if($pay_cover_id==0){
            return $this->apiError('请上传支付凭证...');
        }
        Db::beginTransaction();
        try {
            //改变订单状态
            $order->xianjin_is_pay=1;
            $order->xianjin_pay_at=Carbon::now();
            $order->status_slug='needget';
            $order->status=2;//待收款
            $order->save();
            $file=FileModel::where('id',$pay_cover_id)->first();
            $order->pay_cover()->add($file);
            Db::commit();
            return $this->apiSuccess('操作成功');
        }catch (Exception $e) {
            Db::rollBack();
            return $this->apiError($e->getMessage());
        }
    }

    /**
     * 确认收款
     * @param JWTAuth $auth
     */
    public function trueget(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('order_id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $order=BoxOrderModel::where('id',$order_id)->where('sell_uid',$user->id)->where('status',2)->where('status_slug','needget')->first();
        if(!$order){
            return $this->apiError('订单信息获取失败');
        }
        $item=BoxItemModel::where('id',$order->item_id)->where('user_id',$order->sell_uid)->where('status',1)->first();
        if(!$item){
            return $this->apiError('盲盒信息获取失败');
        }
        Db::beginTransaction();
        try {
            //改变订单状态
            $order->status_slug='needpay_shangjia';
            $order->status=3;//待上架
            $order->save();
            //改变盲盒
            $item->user_id=$order->buy_uid;
            $item->sale=$item->sale+1;
            $item->save();
            //处理奖金
            $bonus_api=new BonusApi();
            $bonus_api->box_bonus($order);
            Db::commit();
            return $this->apiSuccess('操作成功');
        }catch (Exception $e) {
            Db::rollBack();
            return $this->apiError($e->getMessage());
        }
    }
    /**
     * 支付上架费
     * @param JWTAuth $auth
     */
    public function pay_shangjia(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('order_id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $order=BoxOrderModel::where('id',$order_id)->where('buy_uid',$user->id)->where('status',3)->where('status_slug','needpay_shangjia')->first();
        if(!$order){
            return $this->apiError('订单信息获取失败');
        }
        //上一步确认支付后，盲盒已经变为买入用户的了
        $item=BoxItemModel::where('id',$order->item_id)->where('user_id',$user->id)->where('status',1)->first();
        if(!$item){
            return $this->apiError('盲盒信息获取失败');
        }
        Db::beginTransaction();
        try {
            //改变订单状态
            $order->shangjia_is_pay=1;
            $order->shangjia_pay_at=Carbon::now();
            $order->status_slug='shenhe_shangjia';
            $order->save();
            Db::commit();
            return $this->apiSuccess('操作成功');
        }catch (Exception $e) {
            Db::rollBack();
            return $this->apiError($e->getMessage());
        }
    }

}
